package com.wzdigit.wms.basic.service.code;

import java.math.BigDecimal;
import java.util.List;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.framework.Shift;
import com.wzdigit.mes.basic.api.BasicVendorApi;
import com.wzdigit.mes.basic.api.QrCodeParseRulesApi;
import com.wzdigit.mes.basic.dto.QRRuleParamDTO;
import com.wzdigit.mes.basic.dto.QrCodeParseRulesDTO;
import com.wzdigit.mes.basic.dto.VendorDTO;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.dtos.basic.QrGoodsDto;
import com.wzdigit.wms.basic.domain.dtos.inventory.PrintSnDataDto;
import com.wzdigit.wms.basic.enums.QrCodeGoodsEnum;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.inventory.GoodsMapper;
import com.wzdigit.wms.basic.util.common.SeparatorString;

import lombok.extern.slf4j.Slf4j;

/**
 * 二维码解析---服务类
 * @author Administrator
 *
 */
@Service
@Slf4j
public class QrCodeParsingService {

	@Autowired
	private SkuMapper skuMapper;
	
	@Autowired
	private GoodsMapper goodsMapper;
	
	@Reference(version = "${dubbo.consumers.vendor.api:1.0.0}", check = false, timeout = 300000)
    private BasicVendorApi basicVendorApi;
	
	@Reference(version = "${dubbo.consumers.basic.qrCodeParseRules.api:1.0.0}", check = false, timeout = 300000)
    private QrCodeParseRulesApi qrCodeParseRulesApi;
	
	private final static String RULE_CODE = "MaterialBarcodeRule";
	private final static String SPLITCHAR = SeparatorString.ASTERISK;
	
	/**
	 * 根据二维码解析Goods
	 *
	 * @param qrRuleParamStr
	 * @return
	 */
	@SuppressWarnings("incomplete-switch")
	public QrGoodsDto initializeGoodsQrCode(String qrRuleParamStr) {
		// 条码SN，物料编码，供应商编码，供应商批次号，生产批次，datecode
		String goodsSn = null, skuCode = null, vendorCode = null, venLotno = null, prdLot = null, datecode = null;
		// 数量
		BigDecimal qty = null;

		// 二维码规则
		QrCodeParseRulesDTO qrCode = qrCodeParseRulesApi.getDtoByRuleCode(RULE_CODE);
		List<QRRuleParamDTO> ruleParamList = JSONObject.parseArray(qrCode.getRuleParam(), QRRuleParamDTO.class);
		try {
			// 二维码文本数据
			String[] qrRuleParamArray = qrRuleParamStr.split("[" + qrCode.getSplitChar() + "]");
			int index = 0;
			for (QRRuleParamDTO ruleParam : ruleParamList) {
				// 规则字段对应的枚举goods字段
				QrCodeGoodsEnum qrCodeGoodsEnum = QrCodeGoodsEnum.getEnumByCode(ruleParam.getColumnCode());
				String qrRuleValue = qrRuleParamArray[index++];
				switch (qrCodeGoodsEnum) {
				case GOODS_SN:
					goodsSn = qrRuleValue;
					break;
				case SKU_CODE:
					skuCode = qrRuleValue;
					break;
				case VEN_LOTNO:
					venLotno = qrRuleValue;
					break;
				case PRD_LOT:
					prdLot = qrRuleValue;
					break;
				case DATECODE:
					datecode = qrRuleValue;
					break;
				case VENDOR_CODE:
					vendorCode = qrRuleValue;
					break;
				case QTY:
					qty = new BigDecimal(qrRuleValue);
					break;
				}
			}
			// 检验条码、物料编码、数量
			if (goodsSn == null || skuCode == null || qty == null) {
				throw new Exception();
			}
		} catch (Exception e) {
			e.printStackTrace();
			Shift.fatal("SN二维码格式错误，请确认！");
		}

		// 检验SN数量是否小于1
		if(qty.signum() < 1) {
			Shift.fatal(String.format("SN数量[%s]不合法！", qty));
		}

		// 检验SN物料
		Integer skuId = null;
		String descCn = null;
		String unit = null;
		QueryWrapper<Sku> skuQueryWrapper = new QueryWrapper<>();
		skuQueryWrapper.eq("SKU_CODE", skuCode);
		Sku sku = skuMapper.selectOne(skuQueryWrapper);
		if (sku == null) {
			Shift.fatal(String.format("SN物料[%s]不存在！", skuCode));
		} else {
			skuId = sku.getSkuId();
			descCn = sku.getDescCn();
			unit = sku.getBaseUnit();
		}

		// 检验SN供应商
		Integer vendorId = null;
		String vendorName = null;
		if(vendorCode != null) {
			VendorDTO vendor = basicVendorApi.getVendorByCode(vendorCode);
			if(vendor == null || vendor.getVendorId() == null) {
				Shift.fatal(String.format("SN供应商[%s]不存在！", vendorCode));
			} else {
				vendorId = vendor.getVendorId();
				vendorName = vendor.getVendorName();
			}
		}
		
		// 条码实体
		QrGoodsDto qrGoodsDto = new QrGoodsDto();
		qrGoodsDto.setGoodsSn(goodsSn);
		qrGoodsDto.setSkuId(skuId);
		qrGoodsDto.setSkuCode(skuCode);
		qrGoodsDto.setDescCn(descCn);
		qrGoodsDto.setVendorId(vendorId);
		qrGoodsDto.setVendorCode(vendorCode);
		qrGoodsDto.setVendorName(vendorName);
		qrGoodsDto.setVenLotno(venLotno);
		qrGoodsDto.setPrdLot(prdLot);
		qrGoodsDto.setDatecode(datecode);
		qrGoodsDto.setQty(qty);
		qrGoodsDto.setUnit(unit);
		return qrGoodsDto;
	}
	
	/**
	 * 生成二维码标签
	 * 
	 * @param goodsIdList
	 * @return 
	 */
	public List<PrintSnDataDto> generateGoodsLabel(List<Integer> goodsIdList) {
		List<PrintSnDataDto> data = goodsMapper.selectPrintSnData(goodsIdList);
		data.stream().forEach(t -> {
			StringBuffer qrCodeStr = new StringBuffer();
			qrCodeStr.append(t.getSkuCode())													// 物料编码
				.append(SPLITCHAR).append(t.getQty())											// 数量
				.append(SPLITCHAR).append(t.getVendorCode() == null ? "" : t.getVendorCode()) 	// 供应商编码
				.append(SPLITCHAR).append(t.getDatecode() == null ? "" : t.getDatecode())	 	// datecode
				.append(SPLITCHAR).append("")													// 毛重
				.append(SPLITCHAR).append("")													// 净重
				.append(SPLITCHAR).append("")													// 长宽高
				.append(SPLITCHAR).append(t.getPrdLot() == null ? "" : t.getPrdLot())		 	// 生产批次
				.append(SPLITCHAR).append(t.getVenLotno() == null ? "" : t.getVenLotno())		// 供方批次
				.append(SPLITCHAR).append(t.getGoodsSn());										// 条码SN
			t.setQrCodeStr(qrCodeStr.toString());
		});
		return data;
	}
	
	/**
	 * 生成二维码文本
	 * 
	 * @param qrRuleParamStr
	 * @param sn
	 * @param qty
	 * @return
	 */
	public String generateGoodsQrCode(String qrRuleParamStr, String sn, BigDecimal qty) {
		String[] qrRuleParamArray = qrRuleParamStr.split("[" + SPLITCHAR + "]");
		StringBuffer qrCodeStr = new StringBuffer();
		for (int i = 0; i < qrRuleParamArray.length; i++) {
			switch (i) {
			case 0:
				qrCodeStr.append(qrRuleParamArray[i]);						// 物料
				break;
			case 1:
				qrCodeStr.append(SPLITCHAR).append(qty);					// 数量
				break;
			case 9:
				qrCodeStr.append(SPLITCHAR).append(sn);						// 条码SN
				break;
			default:
				qrCodeStr.append(SPLITCHAR).append(qrRuleParamArray[i]);	// 其他参数
				break;
			}
		}
		return qrCodeStr.toString();
	}
}
